//
//  ParseXMLToJson.m
//  SwiftLua
//
//  Created by xiaerfei on 2019/7/28.
//  Copyright © 2019 xiaerfei. All rights reserved.
//

#import "ParseXMLToJson.h"
#import "GDataXMLNode.h"

@implementation ParseXMLToJson

- (void)pathForResource:(NSString *)name ofType:(NSString *)ext {
    NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:ext];
    NSString *xmlString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    [self parseXMLString:xmlString];
}


- (void)parseXMLString:(NSString *)xmlString {
    
    
    NSError *error = nil;
     GDataXMLElement *rootElement = [[GDataXMLDocument alloc] initWithXMLString:xmlString error:&error].rootElement;
    NSArray *array = [self parseElement:@[rootElement] parent:nil];
    NSLog(@"%@",array);
}

- (NSArray *)parseElement:(NSArray<GDataXMLElement *>*)elements parent:(GDataXMLElement *)parent {
    if (elements.count == 0) { return nil; }
    if ([elements.firstObject isKindOfClass:[GDataXMLElement class]] == NO) { return nil; }
    NSMutableArray *eleArray = [NSMutableArray array];
    for (GDataXMLElement *element in elements) {
        NSMutableDictionary *eleDict = [NSMutableDictionary dictionary];
        /*
         name:
         attri:
         subs
         */
        eleDict[@"name"] = element.name;
        NSMutableDictionary *attriDict = [NSMutableDictionary dictionary];
        for (GDataXMLNode *node in element.attributes) {
            attriDict[node.name] = node.stringValue;
        }
        eleDict[@"attri"] = attriDict;
        NSArray *subs = [self parseElement:element.children parent:element];
        eleDict[@"subs"] = subs;
        [eleArray addObject:eleDict];
    }
    
    return eleArray;
}



@end
